Page({
  data: {
    testResults: [],
    testImageUrl: '/uploads/user-examples/659054fa-3b20-4b06-af59-29fdacdc36c8.jpg'
  },

  onLoad() {
    this.runTests();
  },

  async runTests() {
    const results = [];
    const config = require('../../utils/config.js');
    const fullImageUrl = config.API_BASE_URL + this.data.testImageUrl;
    
    console.log('开始测试图片访问...');
    console.log('完整图片URL:', fullImageUrl);
    
    // 测试1: 直接使用wx.request请求图片
    results.push(await this.testWithWxRequest(fullImageUrl));
    
    // 测试2: 测试API连接
    results.push(await this.testApiConnection(config.API_BASE_URL));
    
    // 测试3: 测试健康检查接口
    results.push(await this.testHealthCheck(config.API_BASE_URL));
    
    this.setData({ testResults: results });
  },

  async testWithWxRequest(url) {
    return new Promise((resolve) => {
      wx.request({
        url: url,
        method: 'GET',
        timeout: 10000,
        success: (res) => {
          console.log('wx.request图片测试成功:', res);
          resolve({
            test: 'wx.request图片访问',
            success: true,
            statusCode: res.statusCode,
            data: `响应大小: ${res.data ? res.data.length || 'unknown' : 'no data'}`
          });
        },
        fail: (error) => {
          console.error('wx.request图片测试失败:', error);
          resolve({
            test: 'wx.request图片访问',
            success: false,
            error: error.errMsg || JSON.stringify(error)
          });
        }
      });
    });
  },

  async testApiConnection(baseUrl) {
    return new Promise((resolve) => {
      wx.request({
        url: baseUrl + '/api/ai-image/examples',
        method: 'GET',
        timeout: 5000,
        success: (res) => {
          resolve({
            test: 'API服务检查',
            success: true,
            statusCode: res.statusCode,
            data: JSON.stringify(res.data).substring(0, 100) + '...'
          });
        },
        fail: (error) => {
          resolve({
            test: 'API服务检查',
            success: false,
            error: error.errMsg || JSON.stringify(error)
          });
        }
      });
    });
  },

  async testHealthCheck(baseUrl) {
    return new Promise((resolve) => {
      wx.request({
        url: baseUrl + '/api/ai-image/examples',
        method: 'GET',
        timeout: 5000,
        success: (res) => {
          resolve({
            test: 'API示例接口',
            success: true,
            statusCode: res.statusCode,
            data: `返回数据: ${res.data ? (res.data.data ? res.data.data.length + '条' : 'no data') : 'empty'}`
          });
        },
        fail: (error) => {
          resolve({
            test: 'API示例接口',
            success: false,
            error: error.errMsg || JSON.stringify(error)
          });
        }
      });
    });
  },

  retryTests() {
    this.setData({ testResults: [] });
    this.runTests();
  }
});
